<script lang="ts" setup>
import { Dropdown as VDropdown } from "floating-vue";
import { computed, ref, watch } from "vue";
import IconArrowDownLine from "~icons/ri/arrow-down-s-line";

export interface Option {
  label: string;
  value: string;
}
const props = defineProps<{
  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  container?: any;
  containerClass?: string;
  options: Option[];
  filterSort?: (options: Option[], query: string) => number;
}>();

const selectedValue = defineModel<string>({
  default: "",
});

const emit = defineEmits<{
  (event: "select"): void;
}>();

const isFocus = ref(false);
const inputValue = ref<string>("");
const selectedOption = ref<Option | null>(null);
const inputRef = ref<HTMLInputElement | null>(null);

const displayLabel = computed(() => {
  if (selectedOption.value) {
    return selectedOption.value.label;
  }
  return selectedValue.value;
});

const filterOptions = computed(() => {
  if (!inputValue.value) {
    return props.options;
  }
  return props.options.filter((option) =>
    option.value
      .toLocaleLowerCase()
      .includes(inputValue.value.toLocaleLowerCase())
  );
});

const handleInputFocus = () => {
  isFocus.value = true;
  setTimeout(() => {
    handleScrollIntoView();
  }, 50);
};

const handleInputBlur = () => {
  isFocus.value = false;
  if (inputValue.value) {
    selectedValue.value = inputValue.value;
    inputValue.value = "";
  }
};

const handleSelectOption = (option: Option) => {
  selectedOption.value = option;
  selectedValue.value = option.value;
  inputValue.value = "";
  inputRef.value?.blur();
  emit("select");
};

const selectedIndex = ref(-1);

const handleOptionKeydown = (event: KeyboardEvent) => {
  const key = event.key;
  if (key === "ArrowUp") {
    selectedIndex.value =
      (selectedIndex.value - 1 + filterOptions.value.length) %
      filterOptions.value.length;
    return true;
  }

  if (key === "ArrowDown") {
    selectedIndex.value =
      (selectedIndex.value + 1) % filterOptions.value.length;
    return true;
  }

  if (key === "Enter") {
    if (selectedIndex.value === -1) {
      return true;
    }
    const option = filterOptions.value[selectedIndex.value];
    if (option) {
      handleSelectOption(option);
    }
    return true;
  }
};

watch(
  selectedValue,
  (newValue) => {
    if (newValue) {
      selectedOption.value =
        props.options.find((option) => option.value === newValue) || null;
      selectedIndex.value = props.options.findIndex(
        (option) => option.value === newValue
      );
    }
  },
  {
    immediate: true,
  }
);

watch(
  selectedIndex,
  () => {
    setTimeout(() => {
      handleScrollIntoView();
    });
  },
  {
    immediate: true,
  }
);

const handleScrollIntoView = () => {
  if (selectedIndex.value === -1) {
    return;
  }
  const optionElement = document.querySelector(
    `.select > div:nth-child(${selectedIndex.value + 1})`
  );
  if (optionElement) {
    optionElement.scrollIntoView({
      behavior: "instant",
      block: "nearest",
      inline: "nearest",
    });
  }
};
</script>
<template>
  <VDropdown :triggers="[]" :shown="isFocus" :auto-hide="false" :distance="0" auto-size
    :container="container || 'body'">
    <div class="select-wrapper" @keydown="handleOptionKeydown">
      <div class="select-container">
        <div class="select-input" :class="{
          'is-focus': isFocus,
        }">
          <span class="input-wrapper">
            <input ref="inputRef" v-model="inputValue" class="input-field"
              :placeholder="(isFocus ? displayLabel : '') as string" @focus="handleInputFocus"
              @blur="handleInputBlur" />
          </span>
          <span v-show="!isFocus" class="display-label">
            {{ displayLabel }}
          </span>
          <span class="arrow-icon" @click="inputRef?.focus()">
            <IconArrowDownLine />
          </span>
        </div>
      </div>
    </div>

    <template #popper>
      <div class="popper-wrapper">
        <div class="select-options">
          <template v-if="filterOptions && filterOptions.length > 0">
            <div v-for="(option, idx) in filterOptions" :key="option.value" class="select-option" :class="{
              'is-selected': option.value === selectedValue,
              'is-highlighted': selectedIndex === idx,
            }" @mousedown="handleSelectOption(option)">
              <span class="option-label">
                {{ option.label }}
              </span>
            </div>
          </template>
          <template v-else>
            <div class="select-option">
              <span class="option-label">No options</span>
            </div>
          </template>
        </div>
      </div>
    </template>
  </VDropdown>
</template>
<style lang="scss" scoped>
.select-wrapper {
  position: relative;
  display: inline-block;
  width: 100%;
}

.select-container {
  height: 2rem; // h-8
}

.select-input {
  box-sizing: border-box;
  display: grid;
  grid-template-columns: 1fr auto;
  height: 100%;
  width: 100%;
  cursor: pointer;
  align-items: center;
  border-radius: 0.375rem; // rounded-md
  padding-left: 0.75rem; // px-3
  padding-right: 0.75rem;
  font-size: 0.875rem; // text-sm
  background-color: transparent;
  border: 1px solid transparent;
  transition: background-color 0.2s, border-color 0.2s;

  &:hover:not(.is-focus) {
    background-color: var(--editor-button-hover-bg);
  }

  &.is-focus {
    background-color: var(--editor-background-color);
    border-color: var(--editor-border-color);
  }
}

.input-wrapper {
  position: absolute;
  bottom: 0;
  top: 0;
  background-color: transparent;
}

.input-field {
  margin: 0;
  height: 100%;
  cursor: auto;
  appearance: none;
  border: none;
  background-color: transparent;
  padding: 0;
  outline: none;
}

.display-label {
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 0.875rem; // text-sm
}

.arrow-icon {
  justify-self: end;
}

.popper-wrapper {
  background-color: var(--editor-toolbar-bg);
}

.select-options {
  max-height: 16rem; // max-h-64
  cursor: pointer;
  padding: 0.25rem; // p-1
  overflow-x: hidden;
  overflow-y: auto;
}

.select-option {
  display: flex;
  height: 2rem; // h-8
  width: 100%;
  align-items: center;
  border-radius: 0.375rem; // rounded-md
  padding: 0.25rem 0.75rem; // px-3 py-1
  font-size: 1rem; // text-base

  &:hover {
    background-color: var(--editor-button-hover-bg);
  }

  &.is-selected {
    background-color: var(--editor-button-active-bg);
  }

  &.is-highlighted {
    background-color: var(--editor-button-hover-bg);
  }
}

.option-label {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  font-size: 0.875rem; // text-sm
}
</style>
